/**
 * Author:   YASUO
 * Date:     2018/6/21 10:46
 * Description:
 */
package com.rljk.redis;

import com.rljk.config.RedisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by YASUO on 2018/6/21.
 */
@Service
public class RedisPoolFactory {

    @Autowired
    RedisConfig redisConfig;

    private static Map<String,JedisPool> maps = new HashMap<String,JedisPool>();

    @Bean(name = "jedisPool")
    public JedisPool jedisPool(){
        String key = redisConfig.getHost()+":"+redisConfig.getPort();
        JedisPool pool = null;
        if(!maps.containsKey(key)){
            JedisPoolConfig poolConfig = new JedisPoolConfig();
            poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
            poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
            poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);
            pool = new JedisPool(poolConfig,redisConfig.getHost(),redisConfig.getPort(),
                    redisConfig.getTimeout() * 1000,redisConfig.getPassword(),0);
            maps.put(key, pool);
        } else {
            pool = maps.get(key);
        }
        return pool;
    }
}
